package com.example.commons;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by Renzhiping on 2018/1/16.
 */
public class Interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {

        if (handler instanceof HandlerMethod) {
            StringBuilder sb = new StringBuilder();
            HandlerMethod h = (HandlerMethod) handler;
            sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
            sb.append("Method    : ").append(h.getMethod().getName()).append("\n");
            sb.append("Params    : ").append(getParamString(request.getParameterMap())).append("\n");
            sb.append("URI       : ").append(request.getRequestURL()).append("\n");
            request.setAttribute("sb",sb);
            System.out.println(sb.toString());
        }
        return true;
    }

    private String getParamString(Map<String, String[]> map) {
               StringBuilder sb = new StringBuilder();
             for(Entry<String,String[]> e:map.entrySet()){
                    sb.append(e.getKey()).append("=");
                     String[] value = e.getValue();
                     if(value != null && value.length == 1){
                              sb.append(value[0]).append("\t");
                           }else{
                               sb.append(Arrays.toString(value)).append("\t");
                         }
                    }
              return sb.toString();
           }

    @Override
    public void postHandle( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView ) throws Exception {

    }

    @Override
    public void afterCompletion( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e ) throws Exception {

    }
}
